<?php
defined('_JEXEC') or die('Restricted access');

class igcategoriesController extends igbaseController
{
	protected $redirect = 'index.php?option=com_igallery';
	
	function __construct($config = array())
	{
		parent::__construct($config);
	
		$this->registerTask('apply', 'save');
	}
	
	function display()
	{
		$view = JRequest::getCmd('view','igcategories');
		
		if($view == 'add_edit_category')
		{
			$model = $this->getModel('add_edit_category');
		
			if( !$model->checkProfileExists() )
			{
				JFactory::getApplication()->enqueueMessage( JText::_( 'PLEASE CREATE PROFILE FIRST' ) );
				$this->setRedirect('index.php?option=com_igallery&controller=igprofile');
				return;
			}
		}
	
		parent::display();
	}
	
	function add_category_redirect()
	{
		//the add button uses post to navigate, this is a bit more RESTful
		$this->setRedirect('index.php?option=com_igallery&view=add_edit_category');
	}
	
	function save()
	{
		$post	= JRequest::get('post');
		
		if(strlen($_FILES['upload_image']['name']) > 2 )
		{
			$fileName = $_FILES['upload_image']['name'];
			$tmpPath = $_FILES['upload_image']['tmp_name'];
			$uploadError = $_FILES['upload_image']['error'];
			
			if(!$fileArray = igFileHelper::processUploadedImage($fileName, $tmpPath, $uploadError, 'igallery', true) )
			{
				return false;
			}
			$post['menu_image_filename'] = $fileArray['filename'];
			
			$configArray =& JComponentHelper::getParams('com_igallery');
			
			if($configArray->get('import_exif_data', 0) == 1)
			{
				$post['menu_description'] = $fileArray['exif_des'];
			}
		}
		
		$model = $this->getModel();
		
		if(!$model->save($post)) 
		{
			JError::raise(2, 500, $model->getError() );
			$msg = '';
		}
		else
		{
			$msg = JText::_('CATEGORY SAVED');
		}
		
		switch($this->_task)
		{
			case 'apply':
			$cid = JRequest::getVar('cid', array(0), '', 'array');
			$id = (int)$cid[0];
			$url = 'index.php?option=com_igallery&view=add_edit_category&cid[]='.$id;
			break;
			
			case 'save':
			$url = 'index.php?option=com_igallery';
		}
		
		$this->setRedirect($url, $msg);
	}
	
	function save_config()
	{
		$table =& JTable::getInstance('component');
		if (!$table->loadByOption( 'com_igallery' ))
		{
			JError::raiseWarning( 500, 'Not a valid component' );
			return false;
		}

		$post = JRequest::get('post');
		$table->bind($post);

		if (!$table->check()) 
		{
			JError::raiseWarning( 500, $table->getError() );
			return false;
		}

		if (!$table->store()) 
		{
			JError::raiseWarning( 500, $table->getError() );
			return false;
		}
	}
}